package cn.shequren.communityPeople.startup.ui;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.ContextWrapper;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.ImageView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.jz.community.basecomm.bean.RegionsBean;
import com.jz.community.basecomm.loaction.LocTask;
import com.jz.community.basecomm.routerUtils.RouterCommonUtils;
import com.jz.community.basecomm.routerUtils.RouterIntentConstant;
import com.jz.community.basecomm.utils.BaseSpUtils;
import com.jz.community.commview.view.CircularAnim;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.shequren.communityPeople.R;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by Tony.Fan on 2018/3/23 15:22
 * 引导页
 */
@Route(path = RouterIntentConstant.APP_MODULE_STARTUP_GUIDE)
public class GuideActivity extends Activity implements ViewPagerAdapter.PagerOnclick {

    @BindView(R.id.guideViewPager)
    ViewPager mViewPager;
    @BindView(R.id.vv_preview)
    PreviewVideoView mVideoView;
    private CompositeDisposable compositeDisposable;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_guide);
        ButterKnife.bind(this);
        mViewPager.setCurrentItem(0);
        mVideoView.setVideoURI(Uri.parse(getVideoPath()));
        List<ImageView> list = new ArrayList<ImageView>();
        for (int i = 0; i < 4; i++) {
            ImageView imageView = new ImageView(this);
            list.add(imageView);
        }
        mViewPager.setAdapter(new ViewPagerAdapter(list, this));
        mVideoView.setOnPreparedListener(mp -> {
            mViewPager.addOnPageChangeListener(pageChangeListener);
            mVideoView.start();
            startVideo(1000);
        });

        mViewPager.setCurrentItem(0);
        new LocTask(this, o -> {
            if (o != null) {
                RegionsBean regionsBean = (RegionsBean) o;
                BaseSpUtils.getInstance().setRegionList(GuideActivity.this, regionsBean);
            }
        }).execute();
    }


    ViewPager.OnPageChangeListener pageChangeListener = new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageSelected(int position) {
            if (position == 0) {
                if (!mVideoView.isPlaying()) {
                    mVideoView.seekTo(0);
                    mVideoView.start();
                    startVideo(1000);
                }
            } else if (position == 1) {
                if (!mVideoView.isPlaying()) {
                    mVideoView.seekTo(3100);
                    mVideoView.start();
                    startVideo(1620);
                }
            } else if (position == 2) {
                if (!mVideoView.isPlaying()) {
                    mVideoView.seekTo(5600);
                    mVideoView.start();
                    startVideo(1400);
                }
            } else if (position == 3) {
                if (!mVideoView.isPlaying()) {
                    mVideoView.seekTo(7000);
                    mVideoView.start();
                    startVideo(1300);
                }
            }
        }

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    };


    private String getVideoPath() {
        return "android.resource://" + this.getPackageName() + "/" + R.raw.guide;
    }


    @SuppressLint("CheckResult")
    private void startVideo(int time) {
        Observable.just("1")
                .delay(time, TimeUnit.MILLISECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onNext(String s) {
                        mVideoView.pause();
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


    /**
     * 解决VideoView内存泄露
     */
    @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(new ContextWrapper(newBase) {
            @Override
            public Object getSystemService(String name) {
                if (Context.AUDIO_SERVICE.equals(name)) {
                    return getApplicationContext().getSystemService(name);
                }
                return super.getSystemService(name);
            }
        });
    }


    @Override
    protected void onPause() {
        super.onPause();
        mVideoView.pause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mVideoView.resume();

    }

    private void addDisposable(Disposable disposable) {
        if (compositeDisposable == null) {
            compositeDisposable = new CompositeDisposable();
        }
        compositeDisposable.add(disposable);
    }

    private void dispose() {
        if (compositeDisposable != null) {
            compositeDisposable.dispose();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        dispose();
    }

    @Override
    public void onClickPager(int position, View view) {
        if (position == 3) {
            CircularAnim.fullActivity(this, view)
                    .colorOrImageRes(R.color.white)
                    .go(() -> {
                        RouterCommonUtils.startNoParameterActivity(RouterIntentConstant.APP_MODULE_MAIN);
                        finish();
                    });

        }
    }
}
